#define _ADC_MODULE_
#include "adchandle.h"


uint8_t  ADCConversCycle;
uint16_t ADCResaultSum[ADC_CHANNEL_AMOUNT];

void ADC_IRQHandler()
{
	uint8_t Cnt;
	
	switch(ADC->SC1 & ADC_SC1_ADCH_MASK)
	{
		case ADC_CHANNEL_AD6:
			ADCResaultSum[ADC_RESULT_NUM_0] += ADC_ReadResultReg(ADC);
			ADC_SetChannel( ADC, ADC_CHANNEL_AD7 );
			break;
		case ADC_CHANNEL_AD7:
			ADC_SetChannel( ADC, ADC_CHANNEL_AD12 );
			ADCResaultSum[ADC_RESULT_NUM_1] += ADC_ReadResultReg(ADC);
			break;
		case ADC_CHANNEL_AD12:
			ADC_SetChannel( ADC, ADC_CHANNEL_AD13 );
			ADCResaultSum[ADC_RESULT_NUM_2] += ADC_ReadResultReg(ADC);
			break;
		case ADC_CHANNEL_AD13:
			ADC_SetChannel( ADC, ADC_CHANNEL_AD14 );
			ADCResaultSum[ADC_RESULT_NUM_3] += ADC_ReadResultReg(ADC);
			break;
		case ADC_CHANNEL_AD14:
			ADC_SetChannel( ADC, ADC_CHANNEL_AD15 );
			ADCResaultSum[ADC_RESULT_NUM_4] += ADC_ReadResultReg(ADC);
			break;
		case ADC_CHANNEL_AD15:
			ADC_SetChannel( ADC, ADC_CHANNEL_AD22_TEMPSENSOR );
			ADCResaultSum[ADC_RESULT_NUM_5] += ADC_ReadResultReg(ADC);
			break;
		case ADC_CHANNEL_AD22_TEMPSENSOR:
			ADC_SetChannel( ADC, ADC_CHANNEL_AD23_BANDGAP );
			ADCResaultSum[ADC_RESULT_TEMP] += ADC_ReadResultReg(ADC);
			break;
		case ADC_CHANNEL_AD23_BANDGAP:
			ADC_SetChannel( ADC, ADC_CHANNEL_AD6 );
			ADCResaultSum[ADC_RESULT_BAND_GAP] += ADC_ReadResultReg(ADC);
			ADCConversCycle++;
			break;
		default:
			ADC_SetChannel( ADC, ADC_CHANNEL_AD6 );
			ADCConversCycle = 0;
			break;
	}
	
	if(ADCConversCycle > 15)
	{
		Cnt = ADC_CHANNEL_AMOUNT;
		ADCConversCycle = 0;
		while(Cnt--)
		{
			ADCResult[Cnt] = ADCResaultSum[Cnt] >> 2;
			ADCResaultSum[Cnt] = 0;
		}
	}
}


void AdcInit()
{
	uint8_t Cnt;
	
	SIM->SCGC |= SIM_SCGC_ADC_MASK;
	
	ADC_IntDisable( ADC );

	/* set clock cource for ADC */
    ADC_SelectClock(ADC,CLOCK_SOURCE_BUS_CLOCK_DIVIDE_2);

    /* set clock divide */
    ADC_SelectClockDivide(ADC,ADC_ADIV_DIVIDE_8);

    /* set ADC mode */
    ADC_SetMode(ADC,ADC_MODE_12BIT);

    /* set FIFO level */
    ADC_SetFifoLevel(ADC,ADC_FIFO_DISABLE);
	
	ADC_VrefSelect( ADC, 0 );

    /* set pin control */
    ADC->APCTL1 = 0xF0C0;
	

	
	ADC_CompareDisable(ADC);          
	ADC_SingleConversion( ADC );
	ADC_SetSoftwareTrigger( ADC );
	ADC_SetLowPower( ADC );
	ADC_FifoScanModeDisable( ADC );
	ADC_SetLongSample(ADC);
	
	ADCConversCycle = 0;

	Cnt = ADC_CHANNEL_AMOUNT;
	while(Cnt--)
	{
		ADCResult[Cnt] = 0;
		ADCResaultSum[Cnt] = 0;
	}
	
	NVIC_SetPriority(ADC_IRQn, 0xFF);
	NVIC_ClearPendingIRQ(ADC_IRQn);
	NVIC_EnableIRQ( ADC_IRQn );
	
	ADC_SetChannel( ADC, ADC_CHANNEL_AD6 );
	ADC_IntEnable( ADC );
}
